package com.question.common.advice;

import com.alibaba.fastjson2.JSON;
import com.question.common.constants.StringConstants;
import com.question.common.model.vo.ResponseVO;
import lombok.extern.slf4j.Slf4j;
import org.jetbrains.annotations.NotNull;
import org.slf4j.MDC;
import org.springframework.core.MethodParameter;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import java.util.Objects;

/**
 * unified response result processing
 *
 * @author star
 */
@Slf4j
@RestControllerAdvice
public class GlobalResponseBodyAdvice implements ResponseBodyAdvice<Object> {

    @Override
    public boolean supports(@NotNull MethodParameter methodParameter, @NotNull Class<? extends HttpMessageConverter<?>> aClass) {
        return true;
    }

    @Override
    public Object beforeBodyWrite(Object body, @NotNull MethodParameter methodParameter, @NotNull MediaType mediaType, @NotNull Class<? extends HttpMessageConverter<?>> aClass, @NotNull ServerHttpRequest serverHttpRequest, @NotNull ServerHttpResponse serverHttpResponse) {
        ResponseVO<Object> response = new ResponseVO<>();
        response.setCode(HttpStatus.OK.value());
        response.setMessage(StringConstants.SUCCESS);
        response.setTraceId(MDC.get(StringConstants.TRACE_ID));
        if (Objects.isNull(body)) {
            return response;
        } else if (body instanceof ResponseVO) {
            return body;
        } else if (body instanceof String) {
            response.setData(body);
            return JSON.toJSONString(response);
        } else {
            response.setData(body);
        }
        return response;
    }

}
